package com.jjb.spider.mqtt.service;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class LoginService {

    @Value("${mqtt.device.authorize.type:}")
    private int deviceAuthorize;

    @Value("${mqtt.device.authorize.url:}")
    private String authorizeUrl;

    public Mono<Boolean> login(String deviceId, String username, String password) {

        if( deviceAuthorize == 0 ) {
            return  Mono.just(true);
        }

        if( deviceAuthorize == 1 ) {
            BodyInserters.FormInserter<Object> formInserter = BodyInserters.fromMultipartData("deviceId", deviceId);
            if(Strings.isNotBlank(username) ) {
                formInserter = formInserter.with("username", username);
            }

            if(Strings.isNotBlank(password)) {
                formInserter = formInserter.with("password", password);
            }

            return WebClient.create()
                    .post()
                    .uri(authorizeUrl)
                    .body(formInserter)
                    .exchangeToMono(clientResponse -> {
                        return Mono.just(clientResponse.statusCode().is2xxSuccessful());
                    });
        } else {
            return Mono.just(false);
        }

    }


}
